﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Collections.Generic;
using System.Text;
using hedefgrup.reports.renault;
using hedefgrup.reports.renault.database;

public partial class adm_dataImport : reportPage
{


    private const string HEADER_VALUE_ROW_TEMPLATE = "<tr><td style='text-align:left;width:30%;background-color:#d0d0d0;'>{0}</td><td style='text-align:left;border-bottom:1px solid #d0d0d0;width:70%;'>{1}</td></tr>";
    private const string HEADER_ROW_TEMPLATE = "<tr><td colspan=2 style='height:40px;width:100%;background-color:#d0d0d0;'>{0}</td></tr>";

    private void renderStep1ForVerbatim()
    {
        StreamReader rdr = new StreamReader(Request.Files[0].InputStream);
        
        int verbatimCount = 0;

        List<string> importData = new List<string>();

        while (!rdr.EndOfStream)
        {
            importData.Add(rdr.ReadLine());
            verbatimCount++;
        }

        string[] firstLineColumns = importData[0].Split('\t');
        StringBuilder htmlBuilder = new StringBuilder();
        htmlBuilder.AppendFormat(HEADER_ROW_TEMPLATE, "FILE ANALYSIS RESULTS");
        htmlBuilder.AppendFormat(HEADER_VALUE_ROW_TEMPLATE, "FILE NAME", Path.GetFileName(Request.Files[0].FileName));
        htmlBuilder.AppendFormat(HEADER_VALUE_ROW_TEMPLATE, "CONTENT TYPE", Request.Files[0].ContentType);
        htmlBuilder.AppendFormat(HEADER_VALUE_ROW_TEMPLATE, "FILE SIZE", Request.Files[0].ContentLength + " bytes");
        htmlBuilder.AppendFormat(HEADER_VALUE_ROW_TEMPLATE, "VERBATIM MONTH AND YEAR", firstLineColumns[0].PadLeft(2, '0') + "-" + firstLineColumns[1]);
        htmlBuilder.AppendFormat(HEADER_VALUE_ROW_TEMPLATE, "NUMBER OF VERBATIMS", verbatimCount);

        div_step_1_html.Text = htmlBuilder.ToString();
        Session["IMPORT_DATA"] = importData;
    }

    private void renderStep1()
    {
        if (Request.Files == null || Request.Files.Count == 0 || Request.Files[0].InputStream.Length == 0) throw new Exception("NO DATA FILE HAS BEEN POSTED. PLEASE SPECIFY A FILE.");

        if (file_type_hdn.Value == "verbatim")
        {
            renderStep1ForVerbatim();
            return;
        }

        textFileParser parser = new textFileParser(Request.Files[0].InputStream);

        if (parser.parsedLines.Count == 0) throw new Exception("EMPTY FILE HAS BEEN POSTED. THE COLUMN INFORMATION COULD NOT BE FOUND");
        
        if (!parser.parsedLines[0].values.Contains("AY")) throw new Exception("THE MONTH INFO FIELD [AY] DOES NOT EXIST IN THE POSTED FILE");
        if (!parser.parsedLines[0].values.Contains("YIL")) throw new Exception("THE MONTH INFO FIELD [YIL] DOES NOT EXIST IN THE POSTED FILE");
        if (!parser.parsedLines[0].values.Contains("BAYII")) throw new Exception("THE MONTH INFO FIELD [BAYII] DOES NOT EXIST IN THE POSTED FILE");
        
        StringBuilder htmlBuilder = new StringBuilder();

        htmlBuilder.AppendFormat(HEADER_ROW_TEMPLATE, "FILE ANALYSIS RESULTS");
        htmlBuilder.AppendFormat(HEADER_VALUE_ROW_TEMPLATE, "FILE NAME", Path.GetFileName(Request.Files[0].FileName));
        htmlBuilder.AppendFormat(HEADER_VALUE_ROW_TEMPLATE, "CONTENT TYPE", Request.Files[0].ContentType);
        htmlBuilder.AppendFormat(HEADER_VALUE_ROW_TEMPLATE, "FILE SIZE", Request.Files[0].ContentLength + " bytes");
        htmlBuilder.AppendFormat(HEADER_VALUE_ROW_TEMPLATE, "NUMBER OF COLUMNS", parser.parsedLines[0].values.Count);
        htmlBuilder.AppendFormat(HEADER_VALUE_ROW_TEMPLATE, "NUMBER OF DATA ROWS", parser.parsedLines.Count - 1);
        htmlBuilder.AppendFormat(HEADER_VALUE_ROW_TEMPLATE, "REPORT MONTH AND YEAR", parser.parsedLines[1].values[parser.parsedLines[0].values.IndexOf("AY")] + " - " + parser.parsedLines[1].values[parser.parsedLines[0].values.IndexOf("YIL")]);

        
        StringBuilder columnListBuilder = new StringBuilder("<table>");
        StringBuilder columnDropDown = new StringBuilder();
        columnDropDown.Append("<option value=''></option>");
        foreach (dataColumn dc in base.getDataCache().getDataColumnDefinitions())
        {
            columnDropDown.AppendFormat("<option value='{0}'>{0} - {1}</option>", dc.columnName, dc.dataType.ToString().Replace("System.", ""));
        }

        foreach(string colName in parser.parsedLines[0].values)
        {
            if (colName != "AY" && colName != "YIL" && colName != "BAYII")
            {
                columnListBuilder.AppendFormat("<tr><td>{0}</td><td><select style='font-family:courier new;' name='col_mapping_{0}'>{1}</select></td></tr>", colName, columnDropDown.ToString().Replace("value='" + colName + "'>", "selected value='" + colName + "'>"));
            }
        }
        columnListBuilder.Append("</table>");
        htmlBuilder.AppendFormat(HEADER_VALUE_ROW_TEMPLATE, "COLUMN LIST", columnListBuilder);
        
        div_step_1_html.Text = htmlBuilder.ToString();

        Session["IMPORT_DATA"] = parser;

    }

    private void renderStep2ForVerbatim()
    {
        Response.Redirect("/adm/dataImportProgress.aspx?verbatim=1");
    }

    private void renderStep2()
    {
        if (base.getString("file_type_hdn") == "flat")
        {
            SortedList<string, string> mappings = new SortedList<string, string>();
            foreach (string key in Request.Form.AllKeys)
            {
                if (key.StartsWith("col_mapping_"))
                {
                    if (!string.IsNullOrEmpty(Request.Form[key]))
                    {
                        if (mappings.ContainsKey(Request.Form[key])) throw new InvalidOperationException("Column " + Request.Form[key] + " specified more than once in the target columns list.");
                        mappings.Add(Request.Form[key], key.Substring("col_mapping_".Length));
                    }
                }
            }
            Session["IMPORT_COLUMN_MAPPING"] = mappings;
        }

        Response.Redirect("/adm/dataImportProgress.aspx?verbatim=" + (base.getString("file_type_hdn") == "verbatim" ? "1" : "0"));
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        base.initialize();
        base.ensureAdministratorIsLoggedIn();

        file_type_hdn.Value = base.getString("file_type");
        if (string.IsNullOrEmpty(file_type_hdn.Value)) file_type_hdn.Value = base.getString("file_type_hdn");

        string senderStep = base.getString("sender");
        div_step_0.Visible = string.IsNullOrEmpty(senderStep);
        div_step_1.Visible = senderStep == "div_step_0";

        try
        {

            switch (senderStep)
            {
                case "div_step_0": renderStep1(); break;
                case "div_step_1": renderStep2(); break;
            }
        }
        catch (Exception exp)
        {
            div_exception.Visible = true;
            div_exception_html.Text = exp.Message;

        }

    }
}
